package com.karry.yl.web.mbassessment;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.karry.commons.base.SuperController;
import com.karry.commons.vo.JsonResponse;
import com.karry.commons.vo.LayTableResponse;
import com.karry.yl.domain.assessment.MbAssessRecords;
import com.karry.yl.domain.elder.Elderly;
import com.karry.yl.service.elder.ElderlyService;
import com.karry.yl.service.mbassessment.MbAssessRecordsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;

/**
 * 老年人能力评估Controller
 */
@Controller
@RequestMapping("/mbassess")
public class MbAssessController extends SuperController {

    @Autowired
    private ElderlyService elderlyService;
    @Autowired
    private MbAssessRecordsService assessRecordsService;
    /**
     * 到达评估页面
     * @return
     */
    @RequestMapping
    public String pgUI(ModelMap modelMap){
        return "mbassessment/mbassess";
    }

    /**
     * 选择老人页面
     * @return
     */
    @RequestMapping("/select/elderly")
    public String selectElderlyUI(){
        return "assessment/selectElderly";
    }

    @RequestMapping("/select/elderly/list")
    @ResponseBody
    public LayTableResponse selectElderlyList(int page, int limit, Integer healthCondition, Integer checkedIn, String code, String name){
        Wrapper<Elderly> elderlyWrapper = new EntityWrapper<Elderly>().eq("orgId", currentUser.getOrgId()).eq("deleted",false);
        if(!StringUtils.isEmpty(healthCondition)){
            elderlyWrapper.eq("healthCondition",healthCondition);
        }
        if(!StringUtils.isEmpty(checkedIn)){
            elderlyWrapper.eq("checkedIn",checkedIn);
        }
        if(!StringUtils.isEmpty(code)){
            elderlyWrapper.like("code",code);
        }
        if(!StringUtils.isEmpty(name)){
            elderlyWrapper.like("name",name);
        }
        Page<Elderly> elderlyPage = elderlyService.selectPage(new Page<Elderly>(page, limit),elderlyWrapper);
        return new LayTableResponse(elderlyPage.getRecords(),elderlyPage.getTotal());
    }

    /**
     * 提交评估结果
     * @return
     */
    @RequestMapping("/update")
    @ResponseBody
    public JsonResponse update(MbAssessRecords records){
        if(records.getId()!=null){
            //日常生活
            if(records.getJinshi()!=null){
                int dailyLiving=records.getJinshi()+records.getXizao()+records.getXiushi()+records.getChuanyi()+records.getDabian()+records.getXiaobian()+records.getRuce()+records.getZychuangyi()+records.getPdfoot()+records.getSxfloor();
                records.setDailyLiving(dailyLiving);
                if(dailyLiving>95){
                    records.setDailyLivingGrade(0);
                }else if (dailyLiving>=65 && dailyLiving<=95){
                    records.setDailyLivingGrade(1);
                }else if (dailyLiving>=45 && dailyLiving<=60){
                    records.setDailyLivingGrade(2);
                }else if (dailyLiving<=40 ){
                    records.setDailyLivingGrade(3);
                }
            }
            //精神状态
            if(records.getRenzhi()!=null){
                int mind=records.getRenzhi()+records.getKill()+records.getYiyu();
                records.setMind(mind);
                if(mind==0){
                    records.setMindGrade(0);
                }else if (mind==1){
                    records.setMindGrade(1);
                }else if (mind==2 || mind==3){
                    records.setMindGrade(2);
                }else if (mind>3 ){
                    records.setMindGrade(3);
                }
            }
            if(records.getYishi()!=null){
                int perception=records.getYishi()+records.getShili()+records.getTingli()+records.getGotong();
                records.setPerception(perception);
                if(records.getYishi()==0  && (records.getShili()<=1 || records.getTingli()<=1) && records.getGotong()==0){
                    records.setPerceptionGrade(0);
                }else if (records.getYishi()==0 && (records.getShili()==2 || records.getTingli()==2 || records.getGotong()==1)){
                    records.setPerceptionGrade(1);
                }else if ((records.getYishi()==0 && (records.getShili()==3 || records.getTingli()==3 || records.getGotong()==2)) || (records.getYishi()==1 &&(records.getShili()<=3 ||  records.getTingli()<=3 || records.getGotong()<=2)) ){
                    records.setPerceptionGrade(2);
                }else if ((records.getYishi()<=1 && (records.getShili()==4 || records.getTingli()==4 || records.getGotong()==3)) || records.getYishi()>1){
                    records.setPerceptionGrade(3);
                }
            }
            //社会参与
            if(records.getShenghuo()!=null){
                int social=records.getShenghuo()+records.getJob()+records.getSkdingxiang()+records.getRendingxiang()+records.getShehuinl();
                records.setSocial(social);
                if(social<=2){
                    records.setSocialGrade(0);
                }else if(social>=3 && social<=7){
                    records.setSocialGrade(1);
                }else if(social>=8 && social<=13){
                    records.setSocialGrade(2);
                }else if(social>13 ){
                    records.setSocialGrade(3);
                }
            }
            assessRecordsService.updateById(records);
        }else{
            records.setOrgId(currentUser.getOrgId());
            records.setEvaluator(currentUser.getUserName());
            records.setAssessDate(new Date());
            records.setPgStatus(1);
            records.setAuditStatus(1);
            //日常生活
            if(records.getJinshi()!=null){
                int dailyLiving=records.getJinshi()+records.getXizao()+records.getXiushi()+records.getChuanyi()+records.getDabian()+records.getXiaobian()+records.getRuce()+records.getZychuangyi()+records.getPdfoot()+records.getSxfloor();
                records.setDailyLiving(dailyLiving);
                if(dailyLiving>95){
                    records.setDailyLivingGrade(0);
                }else if (dailyLiving>=65 && dailyLiving<=95){
                    records.setDailyLivingGrade(1);
                }else if (dailyLiving>=45 && dailyLiving<=60){
                    records.setDailyLivingGrade(2);
                }else if (dailyLiving<=40 ){
                    records.setDailyLivingGrade(3);
                }
            }
            //精神状态
            if(records.getRenzhi()!=null){
                int mind=records.getRenzhi()+records.getKill()+records.getYiyu();
                records.setMind(mind);
                if(mind==0){
                    records.setMindGrade(0);
                }else if (mind==1){
                    records.setMindGrade(1);
                }else if (mind==2 || mind==3){
                    records.setMindGrade(2);
                }else if (mind>3 ){
                    records.setMindGrade(3);
                }
            }
              /*感知能力
               * 0 能力完好：意识清醒，且视力和听力评为 0 或 1，沟通评为 0
                1 轻度受损：意识清醒，但视力或听力中至少一项评为 2，或沟通评为 1
                2 中度受损：意识清醒，但视力或听力中至少一项评为 3，或沟通评为 2；
                        或嗜睡，视力或听力评定为 3 及以下，沟通评定为 2 及以下
                3 重度受损：意识清醒或嗜睡，但视力或听力中至少一项评为 4，或沟通评为 3；
                或昏睡/昏迷
               * **/
            if(records.getYishi()!=null){
                int perception=records.getYishi()+records.getShili()+records.getTingli()+records.getGotong();
                records.setPerception(perception);
                if(records.getYishi()==0  && (records.getShili()+records.getTingli())<3 && records.getGotong()==0){
                    records.setPerceptionGrade(0);
                }else if (records.getYishi()==0 && (records.getShili()==2 || records.getTingli()==2 || records.getGotong()==1)){
                    records.setPerceptionGrade(1);
                }else if ((records.getYishi()==0 && (records.getShili()==3 || records.getTingli()==3 || records.getGotong()==2)) || (records.getYishi()==1 && (records.getShili()<=3 ||  records.getTingli()<=3) && records.getGotong()<=2) ){
                     records.setPerceptionGrade(2);
                }else if ((records.getYishi()<=1 && (records.getShili()==4 || records.getTingli()==4 || records.getGotong()==3)) || records.getYishi()>1){
                    records.setPerceptionGrade(3);
                }
            }
            //社会参与
            if(records.getShenghuo()!=null){
                int social=records.getShenghuo()+records.getJob()+records.getSkdingxiang()+records.getRendingxiang()+records.getShehuinl();
                records.setSocial(social);
                if(social<=2){
                    records.setSocialGrade(0);
                }else if(social>=3 && social<=7){
                    records.setSocialGrade(1);
                }else if(social>=8 && social<=13){
                    records.setSocialGrade(2);
                }else if(social>13 ){
                    records.setSocialGrade(3);
                }
            }
            assessRecordsService.insert(records);
        }
        return JsonResponse.success(records);
    }

    /**
     *注：老年人能力初步等级划分标准
     * 0 能力完好：
     * 日常生活活动、精神状态、感知觉与沟通分级均为 0，社会参与分级为 0 或 1
     * 1 轻度失能：
     * 日常生活活动分级为 0，但精神状态、感知觉与沟通中至少一项分级为 1 及以上，或社会参与的分级为 2；
     * 或日常生活活动分级为 1，精神状态、感知觉与沟通、社会参与中至少有一项的分级为 0 或 1
     * 2 中度失能：
     * 日常生活活动分级为 1，但精神状态、感知觉与沟通、社会参与均为 2，或有一项为 3；
     * 或日常生活活动分级为 2，且精神状态、感知觉与沟通、社会参与中有 1-2 项的分级为 1 或 2
     * 3 重度失能：
     * 日常生活活动的分级为 3；
     * 或日常生活活动、精神状态、感知觉与沟通、社会参与分级均为 2；
     * 或日常生活活动分级为 2，且精神状态、感知觉与沟通、社会参与中至少有一项分级为 3
     *
     * 1 有认知障碍/痴呆、精神疾病者，在原有能力级别上提高一个等级；
     * 2 近 30 天内发生过 2 次及以上跌倒、噎食、自杀、走失者，在原有能力级别上提高一
     * 个等级；
     * 3 处于昏迷状态者，直接评定为重度失能；
     * 4 若初步等级确定为“3 重度失能”，则不考虑上述 1-3 中各情况对最终等级的影响，
     * 等级不再提高
     *
     *  查询评估结果
     * */
    @RequestMapping("/selectPgbg")
    @ResponseBody
    public JsonResponse selectPgbg(Long id){
        MbAssessRecords record=assessRecordsService.selectById(id);
        //判断有没有提交完所有项,如果提交完成则计算最终评估结果
        if(record.getStupid()!=null && record.getJinshi()!=null && record.getRenzhi()!=null && record.getYishi()!=null && record.getShenghuo()!=null){
            int shenghuo=record.getDailyLivingGrade();
            int jingshen=record.getMindGrade();
            int ganzhi=record.getPerceptionGrade();
            int shehui=record.getSocialGrade();
            int chubupd=-1;
            if(shenghuo==0 && jingshen==0 && ganzhi==0 && shehui<=1 ){
                chubupd=0;
            }else if( (shenghuo==0 && (jingshen>=1 || ganzhi>=1 || shehui==2)) || (shenghuo==1 && (jingshen<=1 || ganzhi<=1 || shehui<=1)) ){
                chubupd=1;
            }else if( (shenghuo==1 && ((jingshen==2 && ganzhi==2 && shehui==2) || (jingshen==3 || ganzhi==3 || shehui==3)))
                    || (shenghuo==2 && ((jingshen<=2 && ganzhi<=2 && shehui<=2) && ((jingshen+ganzhi+shehui)<6 && (jingshen+ganzhi+shehui) >=2))) ){
                chubupd=2;
            }else if(shenghuo==3 || (shenghuo ==2 && jingshen==2 && ganzhi==2 && shehui==2) || (shenghuo==2 && (jingshen==3 || ganzhi==3 || shehui==3))){
                chubupd=3;
            }
            int stupid=record.getStupid();//痴呆
            int spirit=record.getSpirit();//精神疾病
            int fall=record.getFall();//跌倒
            int lost=record.getLost();//走失
            int foraging=record.getForaging();//噎食
            int suicide=record.getSuicide();//自杀
            int yishi=record.getYishi();//意识
            MbAssessRecords recos=new MbAssessRecords();
            recos.setId(id);
            recos.setPgStatus(2);
            if(chubupd==3 || yishi==3){
                recos.setRs(3);
            }else if(stupid>0 || spirit>0 || fall>1 || lost>1 || foraging>1 || suicide>1){
                recos.setRs(chubupd+1);
            }else {
                recos.setRs(chubupd);
            }
            Elderly elderly = elderlyService.selectById(record.getElderlyId());
            if (recos.getRs()==0){
                    elderly.setPgjg("能力完好");
            }else if (recos.getRs()==1){
                elderly.setPgjg("轻度失能");
            }else if (recos.getRs()==2){
                elderly.setPgjg("中度失能");
            }else if (recos.getRs()==3){
                elderly.setPgjg("重度失能");
            }
            elderlyService.updateById(elderly);
            assessRecordsService.updateById(recos);
            record=assessRecordsService.selectById(id);
            record.setChubupd(chubupd);
        }
        return JsonResponse.success(record);
    }

    /**
     * 继续评估
     * @return
     */
    @RequestMapping("/gopg")
    public String gopg(Long id,ModelMap modelMap){
        MbAssessRecords record=assessRecordsService.selectById(id);
        Elderly elderly=elderlyService.selectById(record.getElderlyId());
        modelMap.put("record",record);
        modelMap.put("elderly",elderly);
        return "mbassessment/editmbassess";
    }
    /**
     * 查看评估
     * @return
     */
    @RequestMapping("/showpg")
    public String showpg(Long id,ModelMap modelMap){
        MbAssessRecords record=assessRecordsService.selectById(id);
        Elderly elderly=elderlyService.selectById(record.getElderlyId());
        String biangeng="";
        if (record.getYishi()==3){
            biangeng="处于昏迷状态，直接评定为重度失能；";
        }else if (record.getStupid()>0 || record.getSpirit()>0){
            biangeng="有认知障碍/痴呆、精神疾病者;";
        }else if (record.getFall()>1 || record.getLost()>1 || record.getForaging()>1 || record.getSuicide()>1){
            biangeng="近 30 天内发生过 2 次及以上跌倒、噎食、自杀、走失;";
        }
        modelMap.put("record",record);
        modelMap.put("biangeng",biangeng);
        modelMap.put("elderly",elderly);
        return "mbassessment/showmbassess";
    }
}
